package zhieasy.cn.xpu_helper.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import zhieasy.cn.common.utils.result.ResultUtils;
import zhieasy.cn.model.common.WechatUser;
import zhieasy.cn.xpu_helper.security.exception.NewWechatUserException;
import zhieasy.cn.xpu_helper.security.exception.TokenException;
import zhieasy.cn.xpu_helper.security.exception.WechatCodeException;
import zhieasy.cn.xpu_helper.security.exception.WechatCodeNullException;
import zhieasy.cn.xpu_helper.security.utils.JwtUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录认证失败处理器
 */
@Component("loginFailureHandler")
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Autowired
    HttpSession httpSession;
    @Autowired
    JwtUtils jwtUtils;
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException, ServletException {
        //1.设置响应编码
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = httpServletResponse.getOutputStream();
        String str = null;
        int code = 500;
        if(e instanceof AccountExpiredException){
            str = "账户过期，登录失败!";
        }else if(e instanceof BadCredentialsException){
            str = "用户名或密码错误，登录失败!";
        }else if(e instanceof CredentialsExpiredException){
            str = "密码过期，登录失败!";
        }else if(e instanceof DisabledException){
            str = "账户被禁用，登录失败!";
        }else if(e instanceof LockedException){
            str = "账户被锁，登录失败!";
        }else if(e instanceof InternalAuthenticationServiceException){
            str = "账户不存在，登录失败!";
        }else if(e instanceof TokenException){
            //token异常
            code = 600;
            str = e.getMessage();
        }else if (e instanceof NewWechatUserException){
            //这里是因为虽然是异常，但是是因为他第一次登录没有这个人的信息所造成的，所以跟别的异常不一样
            code = 100;
            str = "游客身份";
            WechatUser wechatUser = (WechatUser) httpSession.getAttribute("wechatUser");
            //2.生成token
            String token = jwtUtils.generateToken(wechatUser);
            Map<String,String> info = new HashMap<>();
            info.put("token",token);
            String res = JSONObject.toJSONString(ResultUtils.error(str,code,info), SerializerFeature.DisableCircularReferenceDetect);
            out.write(res.getBytes("UTF-8"));
            out.flush();
            out.close();
            return;
        }else if(e instanceof WechatCodeException){
            str = "wechatCode有问题，请重新发送";
        }else if(e instanceof WechatCodeNullException){
            str = "wechatCode为空，请使用post请求并且添加wechatCode";
        }else{
            str = "登录失败!";
            e.printStackTrace();
        }
        String res = JSONObject.toJSONString(ResultUtils.error(str,code,null), SerializerFeature.DisableCircularReferenceDetect);
        out.write(res.getBytes("UTF-8"));
        out.flush();
        out.close();
    }
}
